//
//  OALoginViewController.m
//  maocuhuiOASystem
//
//  Created by michael on 16/3/20.
//  Copyright © 2016年 czd. All rights reserved.
//
#import "GSKeyChainDataManager.h"

#import <ifaddrs.h>
#import <arpa/inet.h>
#import "OALoginViewController.h"
#import "MainViewController.h"
#import "XmlParseHelper.h"
#import "AuthHelper.h"
#import "webViewController.h"
#import "MainTabBarController.h"
#import "MenuViewController.h"
#import "ZLCGuidePageView.h"
#import "HttpTools.h"
@interface OALoginViewController ()<UITextFieldDelegate,SangforSDKDelegate>
@property (nonatomic, strong) AuthHelper *helper;
@property(nonatomic,strong)NSArray * array;
@property(nonatomic,strong)NSDictionary * dic2;
@end

@implementation OALoginViewController
short port = 10443;                        //vpn设备端口号，一般为443
NSString *vpnIp =    @"60.190.208.86";  //vpn设备IP地址
NSString *userName = @"jsdqvpn";             //用户名认证的用户名
NSString *password = @"jsdq123456";                //用户名认证的密码

NSString *certName = @"";     //导入证书名字，如果服务端没有设置证书认证可以不设置
NSString *certPwd =  @"";          //证书密码，如果服务端没有设置证书


- (NSString *)getIPAddress {
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            if(temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            temp_addr = temp_addr->ifa_next;
        }
    }
    // Free memory
    freeifaddrs(interfaces);
    return address;
  
}
- (void)viewDidLoad {
 
//    NSString *version = [UIDevice currentDevice].systemVersion;
//
//    if (version.doubleValue >= 13.0) {
//                  self.overrideUserInterfaceStyle = UIUserInterfaceStyleLight;
//      } else {
//          // 针对 11.0 以下的iOS系统进行处理
//      }
NSString *ip = [self getIPAddress];
NSLog(@"------------%@------------",ip);

    [super viewDidLoad];
    
    
    if(![[NSUserDefaults standardUserDefaults]boolForKey:@"firstStart"]){
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
//引导页图片数组
//    NSArray *images =  @[[UIImage imageNamed:@"2、欢迎页面（640x1136）"],[UIImage imageNamed:@"2、欢迎页面（640x1136）"],[UIImage imageNamed:@"2、欢迎页面（640x1136）"],[UIImage imageNamed:@"2、欢迎页面（640x1136）"],[UIImage imageNamed:@"2、欢迎页面（640x1136）"]];
	//创建引导页视图
//	ZLCGuidePageView *pageView = [[ZLCGuidePageView alloc]initWithFrame:self.view.frame WithImages:images];
//	[self.view addSubview:pageView];
}

 if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"name"] isEqualToString:@"Y"]) {
    self.rememberbutton.selected = YES;
    }
     if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"mima"] isEqualToString:@"Y"]) {
        self.autobutton.selected = YES;
    }        // Do any additional setup after loading the view.
   UIImageView *image1 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"password"]];
      image1.frame = CGRectMake(10, 5, 20, 20);
    
//image1.transform = CGAffineTransformMakeTranslation(30, 0);
       //image1.contentMode = UIViewContentModeTopLeft;
   UIView *view1 = [[UIView alloc]init];
   view1.backgroundColor = [UIColor clearColor];
   view1.size = CGSizeMake(30,30);
   [view1 addSubview:image1];
    self.passwordTextField.leftView = view1;
    self.passwordTextField.leftViewMode = UITextFieldViewModeAlways;
UIImageView *image2 = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"user"]];
 image2.frame = CGRectMake(10, 5, 20, 20);
  UIView *view2 = [[UIView alloc]init];
   view2.backgroundColor = [UIColor clearColor];
   view2.size = CGSizeMake(30,30);
   [view2 addSubview:image2];

 
    self.accountTextField.leftView = view2;
    self.accountTextField.leftViewMode = UITextFieldViewModeAlways;
[_buttonlayer.layer setMasksToBounds:YES];

[_buttonlayer.layer setCornerRadius:20.0];//设置矩形四个圆角半径

//[_buttonlayer.layer setBorderWidth:2.0];//边框宽度
UIColor *textColor = self.view.tintColor;

//_buttonlayer.layer.borderColor=textColor.CGColor;
// textfidld
[_accountTextField.layer setMasksToBounds:YES];


[_accountTextField.layer setBorderWidth:2.0];//边框宽度
UIColor *color = [[UIColor whiteColor]colorWithAlphaComponent:.6];

_accountTextField.layer.borderColor=color.CGColor;
[_passwordTextField.layer setMasksToBounds:YES];


[_passwordTextField.layer setBorderWidth:2.0];//边框宽度

_passwordTextField.layer.borderColor=color.CGColor;
if (self.rememberbutton.selected) {
        self.accountTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
    }
    if (self.autobutton.selected) {
        self.passwordTextField.text = [[NSUserDefaults standardUserDefaults] objectForKey:@"pwdId"];
    }

     // 判断版本
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
 CFShow((__bridge CFTypeRef)(infoDictionary));
// app名称
 NSString *app_Name = [infoDictionary objectForKey:@"CFBundleDisplayName"];
 // app版本
_verson= [infoDictionary objectForKey:@"CFBundleShortVersionString"];
[self _shadow];
}
-(void)viewWillAppear:(BOOL)animated{
// self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
//    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
}



- (void)_shadow{
 _accountTextField.layer.shadowOffset =  CGSizeMake(5,5);
    _accountTextField.layer.shadowOpacity = 0.75;
    _accountTextField.layer.shadowColor = [UIColor colorWithHexString:@"0436be" ].CGColor;
_accountTextField.layer.shadowRadius = 5;


}



#pragma Mark VPNDelegate
- (void) onCallBack:(const VPN_RESULT_NO)vpnErrno authType:(const int)authType
{
    switch (vpnErrno)
    {
        case RESULT_VPN_INIT_FAIL:
            NSLog(@"Vpn Init failed!");
            break;
            
        case RESULT_VPN_AUTH_FAIL:
            [self.helper clearAuthParam:@SET_RND_CODE_STR];
            NSLog(@"Vpn auth failed!");
            break;
            
        case RESULT_VPN_INIT_SUCCESS:
            NSLog(@"Vpn init success!");
            //设置认证参数 用户名和密码以数值map的形式传入
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            //开始用户名密码认证
            [self.helper loginVpn:SSL_AUTH_TYPE_PASSWORD];
            break;
        case RESULT_VPN_AUTH_SUCCESS:
            [self startOtherAuth:authType];
            break;
        case RESULT_VPN_AUTH_LOGOUT:
            NSLog(@"Vpn logout success!");
            break;
        case RESULT_VPN_OTHER:
            if (VPN_OTHER_RELOGIN_FAIL == (VPN_RESULT_OTHER_NO)authType) {
                NSLog(@"Vpn relogin failed, maybe network error");
            }
            break;
            
        case RESULT_VPN_NONE:
            break;
            
        default:
            break;
    }
}

- (void) startOtherAuth:(const int)authType
{
    NSArray *paths = nil;
    switch (authType)
    {
        case SSL_AUTH_TYPE_CERTIFICATE:
            paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                        NSUserDomainMask, YES);
            
            if (nil != paths && [paths count] > 0)
            {
                NSString *dirPaths = [paths objectAtIndex:0];
                NSString *authPaths = [dirPaths stringByAppendingPathComponent:certName];
                NSLog(@"PATH = %@",authPaths);
                [self.helper setAuthParam:@CERT_P12_FILE_NAME param:authPaths];
                [self.helper setAuthParam:@CERT_PASSWORD param:certPwd];
            }
            NSLog(@"Start Cert Auth!!!");
            break;
            
        case SSL_AUTH_TYPE_PASSWORD:
            NSLog(@"Start Password Name Auth!!!");
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_NAME param:userName];
            [self.helper setAuthParam:@PORPERTY_NamePasswordAuth_PASSWORD param:password];
            
            break;
        case SSL_AUTH_TYPE_NONE:
            NSLog(@"Auth success!!!");
//            [self upApp];
        
            [self setin];
            return;
        default:
            NSLog(@"Other failed!!!");
            return;
    }
    [self.helper loginVpn:authType];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{

    [self.accountTextField resignFirstResponder];
    [self.passwordTextField resignFirstResponder];
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setin{
[self.accountTextField resignFirstResponder];
[self.passwordTextField resignFirstResponder];
          NSString* identifierNumber = [[UIDevice currentDevice].identifierForVendor UUIDString] ;
NSLog(@"手机序列号: %@",identifierNumber);
// [GSKeyChainDataManager saveUUID:identifierNumber];
 NSString *string = [GSKeyChainDataManager readUUID]; //读取
 
 if (string.length>0) {
    
}else{
 [GSKeyChainDataManager saveUUID:identifierNumber];

}
string = [GSKeyChainDataManager readUUID]; //读取
     NSString *strUrl = [self.accountTextField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
         strUrl = [strUrl lowercaseString];
    NSString *string2 = [NSString stringWithFormat:@"(iOS%@)",KSystemVersion];

    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:strUrl forKey:@"userId"];
     [params setObject:self.passwordTextField.text forKey:@"pwdId"];
[HttpTools postWithURL:KLoginURL arrays:@[@{@"userId":strUrl},@{@"pwdId":self.passwordTextField.text},@{@"device":string},@{@"phonetype":string2}] method:@"validationUser" success:^(id JSON) {

       [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        XmlParseHelper * parse = [[XmlParseHelper alloc]initWithData:JSON];
        NSArray * dataArray = [parse selectNodes:@"errmsg"];
        NSString * resultTag = nil;
        if (dataArray.count) {
            NSDictionary * dic  = [dataArray lastObject];
            resultTag = dic[@"text"];
        }
//         MainViewController * mainVC = [self.storyboard instantiateViewControllerWithIdentifier:@"MainVC"];
//        UINavigationController * navVC = [[UINavigationController alloc]initWithRootViewController:mainVC];
    
//     MainTabBarController *tar = [[MainTabBarController alloc]init];
 [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
[[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];

        MenuViewController *tar = [[MenuViewController alloc]init];

    
    
        switch ([resultTag integerValue]) {
            case 1:
                 [self.view makeToast:@"您的用户名不存在，请确认后再输"];
                break;
                case 2:

               self.view.window.rootViewController = tar;
                if (!self.autobutton.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"mima"];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"mima"];
                }
                 if (!self.rememberbutton.selected) {
                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"name"];
                }else{
                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"name"];
                }

//                if (self.rememberbutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:strUrl forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:self.passwordTextField.text forKey:@"pwdId"];
//                 
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"userId"];
//                    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:@"pwdId"];
//                }
//                
//                if (!self.autobutton.selected) {
//                    [[NSUserDefaults standardUserDefaults] setObject:@"N" forKey:@"autoLogin"];
//                }else{
//                    [[NSUserDefaults standardUserDefaults] setObject:@"Y" forKey:@"autoLogin"];
//                }

                break;
                case 3:
                [self.view makeToast:@"您的密码错误，请确认后再输"];
                break;
                case -1099:
                [self.view makeToast:@"抱歉，服务器出错"];
                break;
            default:
                break;
        }
        
    } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
    }];
}
- (IBAction)LoginAction:(id)sender {
//if ([_type isEqualToString:@"1"]) {
//    [self setin ];
//}
//else{
//    [MBProgressHUD showHUDAddedTo:self.view animated:YES];

if (self.accountTextField.text.length == 0) {
        [self.view makeToast:@"请输入账号"];
        return;
    } 
    if (self.passwordTextField.text.length == 0) {
        [self.view makeToast:@"请输入密码"];
        return;
    }
else{
 MBProgressHUD * hud =  [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                hud.labelText = @"正在登录,请稍等";
                [NSThread sleepForTimeInterval:1.0];

 if([_helper queryVpnStatus] ==VPN_STATUS_OK){
  [self setin];
 
 }else{
  self.helper = [[AuthHelper alloc] initWithHostAndPort:vpnIp port:port delegate:self];
    [self.helper setAuthParam:@AUTO_LOGIN_OFF_KEY param:@"true"];
 
 }
                 }

//}


}
- (IBAction)rememberbutton:(id)sender {
 self.rememberbutton.selected = !self.rememberbutton.selected;
    if (!self.rememberbutton.selected) {
        self.autobutton.selected = self.rememberbutton.selected;
    }
    

}

- (IBAction)autonbutton:(id)sender {
    self.autobutton.selected = !self.autobutton.selected;


//在此实现不打勾时的方法
}
@end
